﻿using UnityEditor;
using UnityEngine;
using System.Collections;

[CustomEditor(typeof(PUEXPlaneColliderAffector))]
public class PUEXPlaneColliderAffectorEditor : Editor {

	public void OnSceneGUI ()
	{
		var affector = target as PUEXPlaneColliderAffector;
		if (!affector.enabled)
			return;
		
		Matrix4x4 defaultMatrix = Handles.matrix;
		if (affector.inWorldSpace) {
			Handles.matrix = Matrix4x4.identity;
		} else {
			Handles.matrix = affector.transform.parent.transform.localToWorldMatrix;
		}
		
		Quaternion quat = Quaternion.LookRotation(affector.normal);
		
		if (Tools.current == Tool.Move) {
			Vector3 value = Handles.PositionHandle (affector.center, Quaternion.identity);
			
			if (GUI.changed) {
				Undo.RecordObject(affector, "PUEXPlaneColliderAffector Modify");
				affector.center = value;
				EditorUtility.SetDirty(affector);
			}
		} else if (Tools.current == Tool.Rotate) {
			quat = Handles.RotationHandle (quat, affector.center);
			Vector3 value = quat * Vector3.forward;
			
			if (GUI.changed) {
				Undo.RecordObject(affector, "PUEXPlaneColliderAffector Modify");
				affector.normal = value;
				EditorUtility.SetDirty(affector);
			}
		}

		float s = HandleUtility.GetHandleSize(affector.center);
		Vector3 p = affector.center + affector.normal * s;
		Handles.DrawLine (affector.center, p);
		Handles.ConeCap(0, p, quat, HandleUtility.GetHandleSize(affector.center) * 0.2f);

		Vector3[] verts = {new Vector3( -s, -s), 
			new Vector3(-s, +s), 
			new Vector3(+s, +s), 
			new Vector3(+s, -s)};
		verts[0] = quat * verts[0] + affector.center;
		verts[1] = quat * verts[1] + affector.center;
		verts[2] = quat * verts[2] + affector.center;
		verts[3] = quat * verts[3] + affector.center;
		Handles.DrawSolidRectangleWithOutline(verts, new Color(Color.yellow.r, Color.yellow.g, Color.yellow.b, 0.3f), Color.yellow);

		Handles.matrix = defaultMatrix;
	}

}
